package montonicstack;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Stack;

public class MonotonicSatck {

    public static void main(String[] args) {

    }

    public int maxA(int[] nums) {
        int n = nums.length; 
        long[] prefixSum = new long[n + 1];
        for (int i = 0; i < n; i++) {
            prefixSum[i + 1] = prefixSum[i] + nums[i];
        }

        int[] left = new int[n];
        int[] right = new int[n];
        Deque<Integer> stack = new ArrayDeque<>();

        // 遍历数组，维护单调递增栈，同时记录左右边界
        for (int i = 0; i < n; i++) {
            while (!stack.isEmpty() && nums[stack.peek()] >= nums[i]) {
                int j = stack.pop();
                right[j] = i;          // j的右边界为当前i
                left[j] = stack.isEmpty() ? -1 : stack.peek(); // j的左边界为栈顶元素
            }
            stack.push(i);
        }

        // 处理栈中剩余元素，它们的右边界为n
        while (!stack.isEmpty()) {
            int j = stack.pop();
            right[j] = n;
            left[j] = stack.isEmpty() ? -1 : stack.peek();
        }

        long max = 0;
        for (int i = 0; i < n; i++) {
            int l = left[i];
            int r = right[i];
            long sum = prefixSum[r] - prefixSum[l + 1]; // 子数组和为(l+1, r-1)
            long current = sum * nums[i];
            if (current > max) {
                max = current;
            }
        }
        return (int) max;
    }
}
